package com.chen.utils;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class PageUtils<T> {
    private Integer pageNum;
    private Integer rowNum;
    private Integer totalPages;
    private Integer totalCount;
    private Integer pageCount = 5;
    private List<T> list;

    /**
     * 集合分页
     *
     * @param resourceList 要分页的集合
     * @param pageIndex    页码
     * @param pageSize     每页条数
     * @return 分页后的集合
     */
    public void initPage(List<T> resourceList, int pageIndex, int pageSize) {
        if (CollectionUtils.isEmpty(resourceList)) {
            this.pageCount = 0;
            this.pageNum = 0;
            this.totalCount = 0;
            this.list = new ArrayList<T>();
        } else {
            pageSize= pageSize == 0 ? 100 : pageSize;
            this.pageCount = pageSize;
            this.pageNum = pageIndex;
            this.totalCount = resourceList.size();
            if (pageIndex < 1) {
                pageIndex = 1;
            }
            int size = resourceList.size();
            int pageCount = size / pageSize;
            int fromIndex = (pageIndex - 1) * pageSize;
            int toIndex = fromIndex + pageSize;
            if (toIndex >= size) {
                toIndex = size;
            }
            if (pageIndex > pageCount + 1) {
                fromIndex = 0;
                toIndex = 0;
            }
            this.list = resourceList.subList(fromIndex, toIndex);
        }

    }

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    public Integer getRowNum() {
        return rowNum;
    }

    public void setRowNum(Integer rowNum) {
        this.rowNum = rowNum;
    }

    public Integer getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(Integer totalPages) {
        this.totalPages = totalPages;
    }

    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getPageCount() {
        return pageCount;
    }

    public void setPageCount(Integer pageCount) {
        this.pageCount = pageCount;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }
}
